<?php

namespace app\batch;

use think\Db;

use think\console\Command;
use app\facade\Redis;

use think\console\Input;
use think\console\Output;
use app\models\{Autoorder, AreaPrice, Order, Orderlog, CateSons};

class AutoOrders extends Command
{
    protected $open = false;
    protected function configure()
    {
        $this->setName('AutoOrders')->setDescription('刷单');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        (new Autoorder())->where(['status' => 1])->chunk(20, function ($list) {
            //查询下级订单的总重
            foreach ($list as $lists) {
                if ($lists['endtime'] < date('Y-m-d H:i')) {
                    (new Autoorder())->where('id', $lists['id'])->update(['status' => 2]);
                } elseif ($lists['startime'] < date('Y-m-d H:i')) {
                    $rdsname = 'AutoOrders' . $lists['id'];
                    //先查找上次记录
                    $times =  Redis::get($rdsname);
                    $lists['parpam'] = json_decode($lists['parpam'], true);
                    $lists['price'] = json_decode($lists['price'], true);
                    $prices_to = [];
                    if (count($lists['price']) > 1) {
                        foreach ($lists['price'] as $price) {
                            $ish =  rand(1, 2);
                            if ($ish == 2 && count($prices_to) <= 2) {
                                $prices_to[] = $price;
                            }
                        }
                    }
                    if ((!$times || $times < date('Y-m-d H:i', time() - 600)) && count($prices_to) > 0) {
                        $parpams = rand(1, count($lists['parpam'])) - 1;
                        $ordersn = time() . rand(11111, 99999);
                        $orderdata = [
                            'user_id' => 1,
                            'orders_id' => $lists['rider'],
                            'appointment' => date('Y-m-d H:i:s'),
                            'name' => $lists['parpam'][$parpams]['name'],
                            'mobile' => $lists['parpam'][$parpams]['mobile'],
                            'province' => $lists['provinceid'],
                            'city' =>  $lists['cityid'],
                            'area' =>  $lists['areaid'],
                            'street' =>  $lists['street'],
                            'address' =>  $lists['parpam'][$parpams]['address'],
                            'posaddress' => $lists['posaddress'] ?? '',
                            'lon' =>  $lists['lon'] ?? 0,
                            'lat' =>  $lists['lat'] ?? 0,
                            'status' => 1,
                            'ordersn' => $ordersn,
                            'ridermessage' => $lists['rider'],
                            'issystem' => 2,
                            'info' => !empty($data['info']) ? $data['info'] : '',
                        ];
                        $orderlog = [];
                        foreach ($prices_to as $prices) {
                            $areaprice = (new AreaPrice())->where(['id' => $prices])->find();
                            $CateSons = (new CateSons())->where(['id' => $areaprice['catsonsid']])->find();
                            $orderlog[] = [
                                'ordersn' => $ordersn,
                                'areapriceid' => $areaprice['id'],
                                'money' =>  $areaprice['price'],
                                'type' => 0,
                                'icon' => $CateSons['icon'] ?? '',
                                'unmit' => $areaprice['unmit'] ?? '公斤',
                                'name' => $CateSons['name'] ?? ''
                            ];
                        }
                        Db::startTrans();
                        try {
                            (new Order())->allowfield(true)->save($orderdata);
                            (new Orderlog())->insertAll($orderlog);
                            Redis::setex($rdsname, 3600, date('Y-m-d H:i'));
                            Db::commit();
                        } catch (\Exception $exception) {
                            dump($exception->getMessage());
                            Db::rollback();
                            echo '成功';
                        }
                        echo '成功';
                    }
                }
            }
        });
    }
}
